package com.ruoyi.utils.msg;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.SSL.service.ISslApplyService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.spring.SpringUtils;

import java.util.ArrayList;

/**
 * 邮箱发送工具
 */
public class EmailUtils {


    private static final ISslApplyService applyService = SpringUtils.getBean(ISslApplyService.class);

    public static AjaxResult sendEmailMsg(String title, String content, String eamils){
        //先获取到发件人配置信息
        AjaxResult aj = applyService.getSendEmailInfo();
        try {
            if(aj.isSuccess()){
                try {
                    //整理内容
                    StringBuilder emailContent = new StringBuilder();
                    for(String jsonStr:content.split(",")){
                        String[] tempItem = jsonStr.split("#");
                        emailContent.append(tempItem[0]+"："+tempItem[2]+"\n");
                    }
                    //得到信息
                    JSONObject accountJson = JSONUtil.parseObj(aj.get("data"));
                    MailAccount account = JSONUtil.toBean(accountJson, MailAccount.class);
                    if(StrUtil.isEmptyIfStr(account.isAuth())){
                        account.setAuth(accountJson.getBool("auth"));
                    }
                    if(StrUtil.isEmptyIfStr(account.isSslEnable())){
                        account.setSslEnable(accountJson.getBool("sslEnable"));
                    }
                    //调用发送邮件的方法
                    MailUtil.send(account, CollUtil.newArrayList(eamils.split(",")), title, emailContent.toString(), false);
                    //插入通知日志
                } catch (Exception e) {
                    Console.error("邮箱发送失败："+e.getMessage());
                    //插入通知日志
                    return AjaxResult.error("发送失败！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return aj;
    }

    public static void main(String[] args) {
        MailAccount account = new MailAccount();
        account.setHost("smtp.exmail.qq.com");
        account.setPort(465);
        account.setAuth(true);
        account.setFrom("zjh@yygzs.cn");
        account.setUser("zjh@yygzs.cn");
        account.setPass("Aa090909");
        account.setSslEnable(true);
        //调用发送邮件的方法
        MailUtil.send(account, CollUtil.newArrayList("1729003905@qq.com".split(",")), "[ssl-test01.yygzs.org]证书签发成功！", "测试", false);
    }
}
